package com.oyesgo.statistics.time;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;

import com.oyesgo.statistics.log.LogUtils;

/**
 * @FileName TimeSercice.java
 * @Description: 定时器服务接口
 * @author rose
 * @version 1.0
 * <p>Company: OYESGO</p>
 * <p>Copyright: Copyright (c) 2010</p>
 */
public class TimeSercice {
	
	private static final long TIME_STAMP = 1000*60*60*24;	//每隔一天
	public static final String DATE_FORMAT_10 = "yyyy-MM-dd";
	public static final String FORMAT = "yyyy-MM-dd HH:mm:ss";
	
	public void execute(){
        Timer timer = new Timer();
        TimeTast myTimeTask = new TimeTast();
        Date date = getFirstExecuteTime();
        /**
         * myTimeTask 指定执行的线程 date 指定第一次日期执行的时间 timestamp 指定每格多久再次执行一次
         */
        timer.schedule(myTimeTask, date, TIME_STAMP);//第二天7点执行以后每隔24小时执行一次
        LogUtils.printlnToFile("[定时器开启] [首次执行时间:"+simpleDateFormat(date)+"] [每隔1天执行1次]");
        
    }
	/**
	 * 得到首次执行时间 第二天7点执行
	 * @return
	 * Date
	 * @author rose
	 */
	public static Date getFirstExecuteTime(){
		Date date = null;
		String dateString = getYesterdayByType(DATE_FORMAT_10, 1);//得到第二天的日期字符串
		String timeString = " 07:00:00";
		String dateTime = dateString+timeString;
		SimpleDateFormat format = new SimpleDateFormat(FORMAT);
		try {
			date = format.parse(dateTime);
		} catch (ParseException e) {
			System.out.println("时间转换异常");
			e.printStackTrace();
		}
		return date;
	}
	/**
	 * 按照格式得到今天向前或者向后的指定日期
	 * @param type
	 * @return
	 * String
	 * @author rose
	 */
	@SuppressWarnings("static-access")
	public static String getYesterdayByType(String type,int n){
		String yesterdayStr = "";
		if (type == null || "".equals(type)) {
			return yesterdayStr;
		}
		Calendar calendar = Calendar.getInstance();
		SimpleDateFormat simpleFormat = new SimpleDateFormat(type);
		Date today = new Date();
		calendar.setTime(today);
		calendar.add(calendar.DATE, n);//得到今天以前或者以后n天的日期
		yesterdayStr = simpleFormat.format(calendar.getTime());
		return yesterdayStr;
	}
	public static String simpleDateFormat(Date date){
		if (date == null) {
			date = new Date();
		}
		SimpleDateFormat format = new SimpleDateFormat(FORMAT);
		String str = format.format(date);
		return str;
	}
}